home *** CD-ROM | disk | FTP | other *** search
/ Complete Linux / Complete Linux.iso / docs / apps / sound / players / mp02_tar.z / mp02_tar / mp02 / midifile.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-01-31  |  18.9 KB  |  889 lines

  1. /*
  2.  * midifile 1.11
  3.  * 
  4.  * Read and write a MIDI file.  Externally-assigned function pointers are 
  5.  * called upon recognizing things in the file.
  6.  *
  7.  * Original release ?
  8.  * June 1989 - Added writing capability, M. Czeiszperger.
  9.  *
  10.  *          The file format implemented here is called
  11.  *          Standard MIDI Files, and is part of the Musical
  12.  *          instrument Digital Interface specification.
  13.  *          The spec is avaiable from:
  14.  *
  15.  *               International MIDI Association
  16.  *               5316 West 57th Street
  17.  *               Los Angeles, CA 90056
  18.  *
  19.  *          An in-depth description of the spec can also be found
  20.  *          in the article "Introducing Standard MIDI Files", published
  21.  *          in Electronic Musician magazine, April, 1989.
  22.  * 
  23.  */
  24. #include "midifile.h"
  25. #define NULLFUNC 0
  26. #define NULL 0
  27.  
  28. #define THINK
  29.  
  30. #ifdef THINK
  31. #include <stdlib.h>
  32. #endif
  33.  
  34. #include <stdio.h>
  35. #include <values.h>
  36.  
  37. char *strcpy(), *strcat();
  38. void exit(), free();
  39.  
  40. /* public stuff */
  41.  
  42. /* Functions to be called while processing the MIDI file. */
  43. int (*Mf_getc)() = NULLFUNC;
  44. int (*Mf_error)() = NULLFUNC;
  45. int (*Mf_header)() = NULLFUNC;
  46. int (*Mf_trackstart)() = NULLFUNC;
  47. int (*Mf_trackend)() = NULLFUNC;
  48. int (*Mf_noteon)() = NULLFUNC;
  49. int (*Mf_noteoff)() = NULLFUNC;
  50. int (*Mf_pressure)() = NULLFUNC;
  51. int (*Mf_parameter)() = NULLFUNC;
  52. int (*Mf_pitchbend)() = NULLFUNC;
  53. int (*Mf_program)() = NULLFUNC;
  54. int (*Mf_chanpressure)() = NULLFUNC;
  55. int (*Mf_sysex)() = NULLFUNC;
  56. int (*Mf_arbitrary)() = NULLFUNC;
  57. int (*Mf_metamisc)() = NULLFUNC;
  58. int (*Mf_seqnum)() = NULLFUNC;
  59. int (*Mf_eot)() = NULLFUNC;
  60. int (*Mf_smpte)() = NULLFUNC;
  61. int (*Mf_tempo)() = NULLFUNC;
  62. int (*Mf_timesig)() = NULLFUNC;
  63. int (*Mf_keysig)() = NULLFUNC;
  64. int (*Mf_seqspecific)() = NULLFUNC;
  65. int (*Mf_text)() = NULLFUNC;
  66.  
  67. /* Functions to implement in order to write a MIDI file */
  68. int (*Mf_putc)() = NULLFUNC;
  69. int (*Mf_writetrack)() = NULLFUNC;
  70. int (*Mf_writetempotrack)() = NULLFUNC;
  71.  
  72. int Mf_nomerge = 0;        /* 1 => continue'ed system exclusives are */
  73.                             /* not collapsed. */
  74. int Mf_interactive = 0;        /* 1 => file and track headers are not required */
  75. long Mf_currtime = 0L;        /* current time in delta-time units */
  76.  
  77. /* private stuff */
  78. static long Mf_toberead = 0L;
  79. static long Mf_numbyteswritten = 0L;
  80.  
  81. static long readvarinum();
  82. static long read32bit();
  83. static long to32bit();
  84. static int read16bit();
  85. static int to16bit();
  86. static char *msg();
  87.  
  88. mfread()         /* The only non-static function in this file. */
  89. {
  90.     if ( Mf_getc == NULLFUNC )
  91.         mferror("mfread() called without setting Mf_getc"); 
  92.  
  93.     readheader();
  94.     while ( readtrack() )
  95.         ;
  96. }
  97.  
  98. /* for backward compatibility with the original lib */
  99. midifile()
  100. {
  101.     mfread();
  102. }
  103.  
  104. static
  105. readmt(s)        /* read through the "MThd" or "MTrk" header string */
  106. char *s;
  107. {
  108.     int n = 0;
  109.     char *p = s;
  110.     int c;
  111.  
  112.     while ( n++<4 && (c=(*Mf_getc)()) != EOF ) {
  113.         if ( c != *p++ ) {
  114.             char buff[32];
  115.             (void) strcpy(buff,"expecting ");
  116.             (void) strcat(buff,s);
  117.             mferror(buff);
  118.         }
  119.     }
  120.     return(c);
  121. }
  122.  
  123. static
  124. egetc()            /* read a single character and abort on EOF */
  125. {
  126.     int c = (*Mf_getc)();
  127.  
  128.     if ( c == EOF )
  129.         mferror("premature EOF");
  130.     Mf_toberead--;
  131.     return(c);
  132. }
  133.  
  134. static
  135. readheader()        /* read a header chunk */
  136. {
  137.     int format, ntrks, division;
  138.  
  139.     if (Mf_interactive) {
  140.         Mf_toberead = 0;
  141.         format = 0;
  142.         ntrks = 1;
  143.         division = 96;
  144.     } else {
  145.         if ( readmt("MThd") == EOF )
  146.             return;
  147.  
  148.         Mf_toberead = read32bit();
  149.         format = read16bit();
  150.         ntrks = read16bit();
  151.         division = read16bit();
  152.     }
  153.  
  154.     if ( Mf_header )
  155.         (*Mf_header)(format,ntrks,division);
  156.  
  157.     /* flush any extra stuff, in case the length of header is not 6 */
  158.     while ( Mf_toberead > 0 )
  159.         (void) egetc();
  160. }
  161.  
  162. static
  163. readtrack()         /* read a track chunk */
  164. {
  165.     /* This array is indexed by the high half of a status byte.  It's */
  166.     /* value is either the number of bytes needed (1 or 2) for a channel */
  167.     /* message, or 0 (meaning it's not  a channel message). */
  168.     static int chantype[] = {
  169.         0, 0, 0, 0, 0, 0, 0, 0,        /* 0x00 through 0x70 */
  170.         2, 2, 2, 2, 1, 1, 2, 0        /* 0x80 through 0xf0 */
  171.     };
  172.     long lookfor;
  173.     int c, c1, type;
  174.     int sysexcontinue = 0;    /* 1 if last message was an unfinished sysex */
  175.     int running = 0;    /* 1 when running status used */
  176.     int status = 0;        /* status value (e.g. 0x90==note-on) */
  177.     int needed;
  178.  
  179.     if (Mf_interactive) {
  180.         Mf_toberead = MAXINT;
  181.     } else {
  182.         if ( readmt("MTrk") == EOF )
  183.             return(0);
  184.  
  185.         Mf_toberead = read32bit();
  186.     }
  187.     Mf_currtime = 0;
  188.  
  189.     if ( Mf_trackstart )
  190.         (*Mf_trackstart)();
  191.  
  192.     while ( Mf_interactive || Mf_toberead > 0 ) {
  193.  
  194.         if (Mf_interactive)
  195.             Mf_currtime += 1;
  196.         else    Mf_currtime += readvarinum();    /* delta time */
  197.  
  198.         c = egetc();
  199.  
  200.         if ( sysexcontinue && c != 0xf7 )
  201.             mferror("didn't find expected continuation of a sysex");
  202.  
  203.         if ( (c & 0x80) == 0 ) {     /* running status? */
  204.             if ( status == 0 )
  205.                 mferror("unexpected running status");
  206.             running = 1;
  207.         }
  208.         else {
  209.             status = c;
  210.             running = 0;
  211.         }
  212.  
  213.         needed = chantype[ (status>>4) & 0xf ];
  214.  
  215.         if ( needed ) {        /* ie. is it a channel message? */
  216.  
  217.             if ( running )
  218.                 c1 = c;
  219.             else
  220.                 c1 = egetc();
  221.             chanmessage( status, c1, (needed>1) ? egetc() : 0 );
  222.             continue;;
  223.         }
  224.  
  225.         switch ( c ) {
  226.  
  227.         case 0xff:            /* meta event */
  228.  
  229.             type = egetc();
  230.             lookfor = Mf_toberead - readvarinum();
  231.             msginit();
  232.  
  233.             while ( Mf_toberead > lookfor )
  234.                 msgadd(egetc());
  235.  
  236.             metaevent(type);
  237.             break;
  238.  
  239.         case 0xf0:        /* start of system exclusive */
  240.  
  241.             lookfor = Mf_toberead - readvarinum();
  242.             msginit();
  243.             msgadd(0xf0);
  244.  
  245.             while ( Mf_toberead > lookfor )
  246.                 msgadd(c=egetc());
  247.  
  248.             if ( c==0xf7 || Mf_nomerge==0 )
  249.                 sysex();
  250.             else
  251.                 sysexcontinue = 1;  /* merge into next msg */
  252.             break;
  253.  
  254.         case 0xf7:    /* sysex continuation or arbitrary stuff */
  255.  
  256.             lookfor = Mf_toberead - readvarinum();
  257.  
  258.             if ( ! sysexcontinue )
  259.                 msginit();
  260.  
  261.             while ( Mf_toberead > lookfor )
  262.                 msgadd(c=egetc());
  263.  
  264.             if ( ! sysexcontinue ) {
  265.                 if ( Mf_arbitrary )
  266.                     (*Mf_arbitrary)(msgleng(),msg());
  267.             }
  268.             else if ( c == 0xf7 ) {
  269.                 sysex();
  270.                 sysexcontinue = 0;
  271.             }
  272.             break;
  273.         default:
  274.             badbyte(c);
  275.             break;
  276.         }
  277.     }
  278.     if ( Mf_trackend )
  279.         (*Mf_trackend)();
  280.     return(1);
  281. }
  282.  
  283. static
  284. badbyte(c)
  285. int c;
  286. {
  287.     char buff[32];
  288.  
  289.     (void) sprintf(buff,"unexpected byte: 0x%02x",c);
  290.     mferror(buff);
  291. }
  292.  
  293. static
  294. metaevent(type)
  295. {
  296.     int leng = msgleng();
  297.     char *m = msg();
  298.  
  299.     switch  ( type ) {
  300.     case 0x00:
  301.         if ( Mf_seqnum )
  302.             (*Mf_seqnum)(to16bit(m[0],m[1]));
  303.         break;
  304.     case 0x01:    /* Text event */
  305.     case 0x02:    /* Copyright notice */
  306.     case 0x03:    /* Sequence/Track name */
  307.     case 0x04:    /* Instrument name */
  308.     case 0x05:    /* Lyric */
  309.     case 0x06:    /* Marker */
  310.     case 0x07:    /* Cue point */
  311.     case 0x08:
  312.     case 0x09:
  313.     case 0x0a:
  314.     case 0x0b:
  315.     case 0x0c:
  316.     case 0x0d:
  317.     case 0x0e:
  318.     case 0x0f:
  319.         /* These are all text events */
  320.         if ( Mf_text )
  321.             (*Mf_text)(type,leng,m);
  322.         break;
  323.     case 0x2f:    /* End of Track */
  324.         if ( Mf_eot )
  325.             (*Mf_eot)();
  326.         break;
  327.     case 0x51:    /* Set tempo */
  328.         if ( Mf_tempo )
  329.             (*Mf_tempo)(to32bit(0,m[0],m[1],m[2]));
  330.         break;
  331.     case 0x54:
  332.         if ( Mf_smpte )
  333.             (*Mf_smpte)(m[0],m[1],m[2],m[3],m[4]);
  334.         break;
  335.     case 0x58:
  336.         if ( Mf_timesig )
  337.             (*Mf_timesig)(m[0],m[1],m[2],m[3]);
  338.         break;
  339.     case 0x59:
  340.         if ( Mf_keysig )
  341.             (*Mf_keysig)(m[0],m[1]);
  342.         break;
  343.     case 0x7f:
  344.         if ( Mf_seqspecific )
  345.             (*Mf_seqspecific)(leng,m);
  346.         break;
  347.     default:
  348.         if ( Mf_metamisc )
  349.             (*Mf_metamisc)(type,leng,m);
  350.     }
  351. }
  352.  
  353. static
  354. sysex()
  355. {
  356.     if ( Mf_sysex )
  357.         (*Mf_sysex)(msgleng(),msg());
  358. }
  359.  
  360. static
  361. chanmessage(status,c1,c2)
  362. int status;
  363. int c1, c2;
  364. {
  365.     int chan = status & 0xf;
  366.  
  367.     switch ( status & 0xf0 ) {
  368.     case 0x80:
  369.         if ( Mf_noteoff )
  370.             (*Mf_noteoff)(chan,c1,c2);
  371.         break;
  372.     case 0x90:
  373.         if ( Mf_noteon )
  374.             (*Mf_noteon)(chan,c1,c2);
  375.         break;
  376.     case 0xa0:
  377.         if ( Mf_pressure )
  378.             (*Mf_pressure)(chan,c1,c2);
  379.         break;
  380.     case 0xb0:
  381.         if ( Mf_parameter )
  382.             (*Mf_parameter)(chan,c1,c2);
  383.         break;
  384.     case 0xe0:
  385.         if ( Mf_pitchbend )
  386.             (*Mf_pitchbend)(chan,c1,c2);
  387.         break;
  388.     case 0xc0:
  389.         if ( Mf_program )
  390.             (*Mf_program)(chan,c1);
  391.         break;
  392.     case 0xd0:
  393.         if ( Mf_chanpressure )
  394.             (*Mf_chanpressure)(chan,c1);
  395.         break;
  396.     }
  397. }
  398.  
  399. /* readvarinum - read a varying-length number, and return the */
  400. /* number of characters it took. */
  401.  
  402. static long
  403. readvarinum()
  404. {
  405.     long value;
  406.     int c;
  407.  
  408.     c = egetc();
  409.     value = c;
  410.     if ( c & 0x80 ) {
  411.         value &= 0x7f;
  412.         do {
  413.             c = egetc();
  414.             value = (value << 7) + (c & 0x7f);
  415.         } while (c & 0x80);
  416.     }
  417.     return (value);
  418. }
  419.  
  420. static long
  421. to32bit(c1,c2,c3,c4)
  422. {
  423.     long value = 0L;
  424.  
  425.     value = (c1 & 0xff);
  426.     value = (value<<8) + (c2 & 0xff);
  427.     value = (value<<8) + (c3 & 0xff);
  428.     value = (value<<8) + (c4 & 0xff);
  429.     return (value);
  430. }
  431.  
  432. static
  433. to16bit(c1,c2)
  434. int c1, c2;
  435. {
  436.     return ((c1 & 0xff ) << 8) + (c2 & 0xff);
  437. }
  438.  
  439. static long
  440. read32bit()
  441. {
  442.     int c1, c2, c3, c4;
  443.  
  444.     c1 = egetc();
  445.     c2 = egetc();
  446.     c3 = egetc();
  447.     c4 = egetc();
  448.     return to32bit(c1,c2,c3,c4);
  449. }
  450.  
  451. static
  452. read16bit()
  453. {
  454.     int c1, c2;
  455.     c1 = egetc();
  456.     c2 = egetc();
  457.     return to16bit(c1,c2);
  458. }
  459.  
  460. /* static */
  461. mferror(s)
  462. char *s;
  463. {
  464.     if ( Mf_error )
  465.         (*Mf_error)(s);
  466.     exit(1);
  467. }
  468.  
  469. /* The code below allows collection of a system exclusive message of */
  470. /* arbitrary length.  The Msgbuff is expanded as necessary.  The only */
  471. /* visible data/routines are msginit(), msgadd(), msg(), msgleng(). */
  472.  
  473. #define MSGINCREMENT 128
  474. static char *Msgbuff = NULL;    /* message buffer */
  475. static int Msgsize = 0;        /* Size of currently allocated Msg */
  476. static int Msgindex = 0;    /* index of next available location in Msg */
  477.  
  478. static
  479. msginit()
  480. {
  481.     Msgindex = 0;
  482. }
  483.  
  484. static char *
  485. msg()
  486. {
  487.     return(Msgbuff);
  488. }
  489.  
  490. static
  491. msgleng()
  492. {
  493.     return(Msgindex);
  494. }
  495.  
  496. static
  497. msgadd(c)
  498. int c;
  499. {
  500.     /* If necessary, allocate larger message buffer. */
  501.     if ( Msgindex >= Msgsize )
  502.         biggermsg();
  503.     Msgbuff[Msgindex++] = c;
  504. }
  505.  
  506. static
  507. biggermsg()
  508. {
  509. /*     char *malloc(); */
  510.     char *newmess;
  511.     char *oldmess = Msgbuff;
  512.     int oldleng = Msgsize;
  513.  
  514.     Msgsize += MSGINCREMENT;
  515.     newmess = (char *) malloc( (unsigned)(sizeof(char)*Msgsize) );
  516.  
  517.     if(newmess == NULL)
  518.         mferror("malloc error!");
  519.         
  520.     /* copy old message into larger new one */
  521.     if ( oldmess != NULL ) {
  522.         register char *p = newmess;
  523.         register char *q = oldmess;
  524.         register char *endq = &oldmess[oldleng];
  525.  
  526.         for ( ; q!=endq ; p++,q++ )
  527.             *p = *q;
  528.         free(oldmess);
  529.     }
  530.     Msgbuff = newmess;
  531. }
  532.  
  533. /*
  534.  * mfwrite() - The only fuction you'll need to call to write out
  535.  *             a midi file.
  536.  *
  537.  * format      0 - Single multi-channel track
  538.  *             1 - Multiple simultaneous tracks
  539.  *             2 - One or more sequentially independent
  540.  *                 single track patterns                
  541.  * ntracks     The number of tracks in the file.
  542.  * division    This is kind of tricky, it can represent two
  543.  *             things, depending on whether it is positive or negative
  544.  *             (bit 15 set or not).  If  bit  15  of division  is zero,
  545.  *             bits 14 through 0 represent the number of delta-time
  546.  *             "ticks" which make up a quarter note.  If bit  15 of
  547.  *             division  is  a one, delta-times in a file correspond to
  548.  *             subdivisions of a second similiar to  SMPTE  and  MIDI
  549.  *             time code.  In  this format bits 14 through 8 contain
  550.  *             one of four values - 24, -25, -29, or -30,
  551.  *             corresponding  to  the  four standard  SMPTE and MIDI
  552.  *             time code frame per second formats, where  -29
  553.  *             represents  30  drop  frame.   The  second  byte
  554.  *             consisting  of  bits 7 through 0 corresponds the the
  555.  *             resolution within a frame.  Refer the Standard MIDI
  556.  *             Files 1.0 spec for more details.
  557.  * fp          This should be the open file pointer to the file you
  558.  *             want to write.  It will have be a global in order
  559.  *             to work with Mf_putc.  
  560.  */ 
  561. void 
  562. mfwrite(format,ntracks,division,fp) 
  563. int format,ntracks,division; 
  564. FILE *fp; 
  565. {
  566.     int i; void mf_write_track_chunk(), mf_write_header_chunk();
  567.  
  568.     if ( Mf_putc == NULLFUNC )
  569.         mferror("mfmf_write() called without setting Mf_putc");
  570.  
  571.     if ( Mf_writetrack == NULLFUNC )
  572.         mferror("mfmf_write() called without setting Mf_mf_writetrack"); 
  573.  
  574.     /* every MIDI file starts with a header */
  575.     mf_write_header_chunk(format,ntracks,division);
  576.  
  577.     /* In format 1 files, the first track is a tempo map */
  578.     if(format == 1 && ( Mf_writetempotrack ))
  579.     {
  580.     (*Mf_writetempotrack)();
  581.     }
  582.  
  583.     /* The rest of the file is a series of tracks */
  584.     for(i = 0; i < ntracks; i++)
  585.         mf_write_track_chunk(i,fp);
  586. }
  587.  
  588. void 
  589. mf_write_track_chunk(which_track,fp)
  590. int which_track;
  591. FILE *fp;
  592. {
  593.     unsigned long trkhdr,trklength;
  594.     long offset, place_marker;
  595.     void write16bit(),write32bit();
  596.     
  597.     
  598.     trkhdr = MTrk;
  599.     trklength = 0;
  600.  
  601.     /* Remember where the length was written, because we don't
  602.        know how long it will be until we've finished writing */
  603.     offset = ftell(fp); 
  604.  
  605. #ifdef DEBUG
  606.         printf("offset = %d\n",(int) offset);
  607. #endif
  608.  
  609.     /* Write the track chunk header */
  610.     write32bit(trkhdr);
  611.     write32bit(trklength);
  612.  
  613.     Mf_numbyteswritten = 0L; /* the header's length doesn't count */
  614.  
  615.     if( Mf_writetrack )
  616.     {
  617.         (*Mf_writetrack)(which_track);
  618.     }
  619.  
  620.     /* mf_write End of track meta event */
  621.     eputc(0);
  622.     eputc(meta_event);
  623.     eputc(end_of_track);
  624.  
  625.      eputc(0);
  626.      
  627.     /* It's impossible to know how long the track chunk will be beforehand,
  628.            so the position of the track length data is kept so that it can
  629.            be written after the chunk has been generated */
  630.     place_marker = ftell(fp);
  631.     
  632.     /* This method turned out not to be portable because the
  633.            parameter returned from ftell is not guaranteed to be
  634.            in bytes on every machine */
  635.      /* track.length = place_marker - offset - (long) sizeof(track); */
  636.  
  637. #ifdef DEBUG
  638. printf("length = %d\n",(int) trklength);
  639. #endif
  640.  
  641.      if(fseek(fp,offset,0) < 0)
  642.         mferror("error seeking during final stage of write");
  643.  
  644.     trklength = Mf_numbyteswritten;
  645.  
  646.     /* Re-mf_write the track chunk header with right length */
  647.     write32bit(trkhdr);
  648.     write32bit(trklength);
  649.  
  650.     fseek(fp,place_marker,0);
  651. } /* End gen_track_chunk() */
  652.  
  653.  
  654. void 
  655. mf_write_header_chunk(format,ntracks,division)
  656. int format,ntracks,division;
  657. {
  658.     unsigned long ident,length;
  659.     void write16bit(),write32bit();
  660.     
  661.     ident = MThd;           /* Head chunk identifier                    */
  662.     length = 6;             /* Chunk length                             */
  663.  
  664.     /* individual bytes of the header must be written separately
  665.        to preserve byte order across cpu types :-( */
  666.     write32bit(ident);
  667.     write32bit(length);
  668.     write16bit(format);
  669.     write16bit(ntracks);
  670.     write16bit(division);
  671. } /* end gen_header_chunk() */
  672.  
  673.  
  674. /*
  675.  * mf_write_midi_event()
  676.  * 
  677.  * Library routine to mf_write a single MIDI track event in the standard MIDI
  678.  * file format. The format is:
  679.  *
  680.  *                    <delta-time><event>
  681.  *
  682.  * In this case, event can be any multi-byte midi message, such as
  683.  * "note on", "note off", etc.      
  684.  *
  685.  * delta_time - the time in ticks since the last event.
  686.  * type - the type of meta event.
  687.  * chan - The midi channel.
  688.  * data - A pointer to a block of chars containing the META EVENT,
  689.  *        data.
  690.  * size - The length of the meta-event data.
  691.  */
  692. int 
  693. mf_write_midi_event(delta_time, type, chan, data, size)
  694. unsigned long delta_time;
  695. unsigned int chan,type;
  696. unsigned long size;
  697. unsigned char *data;
  698. {
  699.     int i;
  700.     void WriteVarLen();
  701.     unsigned char c;
  702.  
  703.     WriteVarLen(delta_time);
  704.  
  705.     /* all MIDI events start with the type in the first four bits,
  706.        and the channel in the lower four bits */
  707.     c = type | chan;
  708.  
  709.     if(chan > 15)
  710.         perror("error: MIDI channel greater than 16\n");
  711.  
  712.     eputc(c);
  713.  
  714.     /* write out the data bytes */
  715.     for(i = 0; i < size; i++)
  716.     eputc(data[i]);
  717.  
  718.     return(size);
  719. } /* end mf_write MIDI event */
  720.  
  721. /*
  722.  * mf_write_meta_event()
  723.  *
  724.  * Library routine to mf_write a single meta event in the standard MIDI
  725.  * file format. The format of a meta event is:
  726.  *
  727.  *          <delta-time><FF><type><length><bytes>
  728.  *
  729.  * delta_time - the time in ticks since the last event.
  730.  * type - the type of meta event.
  731.  * data - A pointer to a block of chars containing the META EVENT,
  732.  *        data.
  733.  * size - The length of the meta-event data.
  734.  */
  735. int
  736. mf_write_meta_event(delta_time, type, data, size)
  737. unsigned long delta_time;
  738. unsigned char *data,type;
  739. unsigned long size;
  740. {
  741.     int i;
  742.  
  743.     WriteVarLen(delta_time);
  744.     
  745.     /* This marks the fact we're writing a meta-event */
  746.     eputc(meta_event);
  747.  
  748.     /* The type of meta event */
  749.     eputc(type);
  750.  
  751.     /* The length of the data bytes to follow */
  752.     WriteVarLen(size); 
  753.  
  754.     for(i = 0; i < size; i++)
  755.     {
  756.     if(eputc(data[i]) != data[i])
  757.         return(-1); 
  758.     }
  759.     return(size);
  760. } /* end mf_write_meta_event */
  761.  
  762. void 
  763. mf_write_tempo(tempo)
  764. unsigned long tempo;
  765. {
  766.     /* Write tempo */
  767.     /* all tempos are written as 120 beats/minute, */
  768.     /* expressed in microseconds/quarter note     */
  769.     eputc(0);
  770.     eputc(meta_event);
  771.     eputc(set_tempo);
  772.  
  773.     eputc(3);
  774.     eputc((unsigned)(0xff & (tempo >> 16)));
  775.     eputc((unsigned)(0xff & (tempo >> 8)));
  776.     eputc((unsigned)(0xff & tempo));
  777. }
  778.  
  779. unsigned long 
  780. mf_sec2ticks(secs,division,tempo)
  781. int division;
  782. unsigned int tempo;
  783. float secs;
  784. {    
  785.      return (long)(((secs * 1000.0) / 4.0 * division) / tempo);
  786. }
  787.  
  788. /*
  789.  * Write multi-length bytes to MIDI format files
  790.  */
  791. void 
  792. WriteVarLen(value)
  793. unsigned long value;
  794. {
  795.   unsigned long buffer;
  796.  
  797.   buffer = value & 0x7f;
  798.   while((value >>= 7) > 0)
  799.   {
  800.     buffer <<= 8;
  801.     buffer |= 0x80;
  802.     buffer += (value & 0x7f);
  803.   }
  804.   while(1){
  805.        eputc((unsigned)(buffer & 0xff));
  806.        
  807.     if(buffer & 0x80)
  808.         buffer >>= 8;
  809.     else
  810.         return;
  811.     }
  812. }/* end of WriteVarLen */
  813.  
  814. /* 
  815.  * This routine converts delta times in ticks into seconds. The
  816.  * else statement is needed because the formula is different for tracks
  817.  * based on notes and tracks based on SMPTE times.
  818.  *
  819.  */
  820. double 
  821. mf_ticks2sec(ticks,division,tempo)
  822. int division;
  823. unsigned int tempo;
  824. unsigned long ticks;
  825. {
  826.     double smpte_format, smpte_resolution;
  827.  
  828.     if(division > 0)
  829.         return ((double) (((double)(ticks) * (double)(tempo)) / ((double)(division) * 1000000.0)));
  830.     else
  831.     {
  832.        smpte_format = upperbyte(division);
  833.        smpte_resolution = lowerbyte(division);
  834.        return (double) ((double) ticks / (smpte_format * smpte_resolution * 1000000.0));
  835.     }
  836. } /* end of ticks2sec() */
  837.  
  838.  
  839. /*
  840.  * write32bit()
  841.  * write16bit()
  842.  *
  843.  * These routines are used to make sure that the byte order of
  844.  * the various data types remains constant between machines. This
  845.  * helps make sure that the code will be portable from one system
  846.  * to the next.  It is slightly dangerous that it assumes that longs
  847.  * have at least 32 bits and ints have at least 16 bits, but this
  848.  * has been true at least on PCs, UNIX machines, and Macintosh's.
  849.  *
  850.  */
  851. void 
  852. write32bit(data)
  853. unsigned long data;
  854. {
  855.     eputc((unsigned)((data >> 24) & 0xff));
  856.     eputc((unsigned)((data >> 16) & 0xff));
  857.     eputc((unsigned)((data >> 8 ) & 0xff));
  858.     eputc((unsigned)(data & 0xff));
  859. }
  860.  
  861. void 
  862. write16bit(data)
  863. int data;
  864. {
  865.     eputc((unsigned)((data & 0xff00) >> 8));
  866.     eputc((unsigned)(data & 0xff));
  867. }
  868.  
  869. /* write a single character and abort on error */
  870. eputc(c)            
  871. unsigned char c;
  872. {
  873.     int return_val;
  874.     
  875.     if((Mf_putc) == NULLFUNC)
  876.     {
  877.         mferror("Mf_putc undefined");
  878.         return(-1);
  879.     }
  880.     
  881.     return_val = (Mf_putc)(c);
  882.  
  883.     if ( return_val == EOF )
  884.         mferror("error writing");
  885.         
  886.     Mf_numbyteswritten++;
  887.     return(return_val);
  888. }
  889.